package org.jiamandan.com.config;

import cn.hutool.extra.spring.SpringUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jiamandan.com.cache.CacheNames;
import org.jiamandan.com.constant.BizConstant;
import org.jiamandan.com.entity.RechargeGun;
import org.jiamandan.com.entity.RechargePile;
import org.jiamandan.com.service.IRechargeGunService;
import org.jiamandan.com.service.IRechargePileService;
import org.jiamandan.com.utils.RedisUtil;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Map;

@Slf4j
public class UdpIdleEventHandler extends ChannelInboundHandlerAdapter {

    private InetSocketAddress clientAddress;


    /**
     * 从客户端收到新的数据、读取完成时调用
     *
     * @param ctx
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        log.debug("channel Read Complete");
        ctx.flush();
    }

    //3.关闭完成->UDP是无连接无需关闭
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("监听断电离线客户端：{}",ctx.channel().id());
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        super.handlerRemoved(ctx);
        ctx.flush();
    }

    //2.已关闭的链接链接->UDP是暂时无需处理
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        if (channel instanceof NioSocketChannel) {
            return;
        }
        try {
            super.channelInactive(ctx);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
    }
     private void removeCacheByChannelId() {
        RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
        Map<String, InetSocketAddress> result = (Map<String, InetSocketAddress>) redisUtil.get(CacheNames.UPD_ADDRESS);
        if (result == null) {
            return;
        }
        for (Map.Entry<String, InetSocketAddress> entry : result.entrySet()) {
            if (entry.getValue().getHostString().equals(clientAddress.getAddress())) {
                String pileNo = entry.getKey();
                result.remove(entry.getKey());
                handlerPileOffline(pileNo);
                break;
            }
        }
        redisUtil.set(CacheNames.UPD_ADDRESS, result);
    }

    /**
     * 设备离线设置
     */
    private void handlerPileOffline(String pileNo){
        log.error("Handler设备号离线：" + pileNo);
        if(StringUtils.isEmpty(pileNo)){
            return;
        }
        IRechargePileService iRechargePileService = SpringUtil.getBean(IRechargePileService.class);
        IRechargeGunService iRechargeGunService = SpringUtil.getBean(IRechargeGunService.class);
        //TODO 根据业务处理
        /*RocketMQTemplate rocketMQTemplate = SpringUtil.getBean(RocketMQTemplate.class);
        MQProperties mqProperties = SpringUtil.getBean(MQProperties.class);
        RechargePile rechargePile = iRechargePileService.getByPileNo(pileNo);
        rechargePile.setLiveStatus(BizConstant.OnOffLine.OFFLINE);
        iRechargePileService.updateById(rechargePile);
        UpdateWrapper<RechargeGun> updateWrapper = Wrappers.<RechargeGun>update();
        updateWrapper.set("online_status", BizConstant.OnOffLine.OFFLINE);
        updateWrapper.eq("pile_no", pileNo);
        iRechargeGunService.update(updateWrapper);
        //30分钟如果还没在线就判定离线，如果不在线还没在线就发送异常报告 16
        Message<String> payload = MessageBuilder.withPayload(pileNo).build();
        rocketMQTemplate.asyncSend(mqProperties.getIssueChargeRetryTopic() + ":" + BizEventTag.DEVICE_OFFLINE.name(),
                payload, RocketmqSendCallbackBuilder.commonCallback(), 3000, 16);*/
    }

}
